import 'dart:convert';
import 'dart:ui';

import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:flutter_lifecycle_base/base_state_widget.dart';
import 'package:route_manager/wx_navigator.dart';
import 'package:wallet_home/constant/sp_key_config.dart';
import 'package:wallet_home/model/coin_detail_model/coin_detail_list_model.dart';
import 'package:wallet_home/page/theme/colors.dart';
import 'package:wallet_home/tools/theme_utils.dart';
import 'package:wallet_home/widget/coin_detail_list_widget.dart';
import 'package:wallet_home/widget/coins_manager.dart';
import 'package:wallet_home/widget/trade_order_and_overview.dart';
import 'package:wallet_home/model/wallet_list_model.dart';

import '../image_r.dart';
import '../module_config.dart';

class CoinDetailPage extends BaseStatefulWidget {
  @override
  _CoinDetailPageState createState() => _CoinDetailPageState();
}

class _CoinDetailPageState extends BaseWidgetState<CoinDetailPage>
    with SingleTickerProviderStateMixin {
  // PageController _controller;
  ScrollController _scrollController;

  TabController _tabController;

  List<Widget> _pages;

  List<Widget> _tabs;

  List<CoinDetailModel> allTransferRecordList = List();

  List<CoinDetailModel> transferAccountRecordList = List();

  List<CoinDetailModel> payeeRecordList = List();

  CoinsBean _bean;

  CoinsBean _coinDetailBean;

  bool isFold = false;

  bool isOverlayShow = false;

  bool isFirstEnter = true;

  void getTabList() {
    _tabs = [
      _renderTab(
          Text("${WXLang.$t("home_all", package: ModuleConfig.moduleName)}")),
      _renderTab(Text(
          "${WXLang.$t("home_transfer", package: ModuleConfig.moduleName)}")),
      _renderTab(Text(
          "${WXLang.$t("home_receive", package: ModuleConfig.moduleName)}")),
    ];
  }

  Color buttonTransferColor = Color(0xFFCCA881);
  Color buttonReceivePaymentColor = Colors.grey[800];

  _renderTab(Text text) {
    return Tab(
        child: Container(
      //设置paddingTop为6
      padding: EdgeInsets.only(top: 6),
      //一个列控件
      child: Column(
        //竖直方向居中
        mainAxisAlignment: MainAxisAlignment.center,
        //水平方向居中
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[text],
      ),
    ));
  }

  @override
  void initState() {
    super.initState();
    getTabList();

    //  _controller = PageController(keepPage: true);
    _tabController = new TabController(length: _tabs.length, vsync: this);

    _scrollController = new ScrollController();
    _scrollController.addListener(() {
      print("scroll====>${_scrollController.offset}========>$isOverlayShow");
      if (_scrollController.position.maxScrollExtent -
              _scrollController.offset <
          5) {
        if (!isFold) {
          isFold = true;
          setState(() {});
        }
      } else {
        if (isFold) {
          isFold = false;
          setState(() {});
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    _bean = ModalRoute.of(context).settings.arguments;
    _coinDetailBean = CoinManager().getSingleCoinDetailModel(_bean.title);

    if (isFirstEnter) {
      buttonTransferColor = ThemeUtils.getThemeColor(
          context: context,
          brightnessColor: Colours.transfer_button,
          darkColor: Colours.color_gold);
      buttonReceivePaymentColor = ThemeUtils.getThemeColor(
          context: context,
          brightnessColor: Colours.payee_button,
          darkColor: Colors.grey[800]);
      isFirstEnter = false;
    }

    return Scaffold(
      body: MediaQuery.removePadding(
          removeTop: true,
          context: context,
          child: SafeArea(
              child: GestureDetector(
            onTapDown: (down) {
              if (isOverlayShow) {
                setState(() {
                  isOverlayShow = false;
                });
              }
            },
            onPanDown: (down) {
              if (isOverlayShow) {
                setState(() {
                  isOverlayShow = false;
                });
              }
            },
            child: Stack(
              children: [
                DefaultTabController(
                    length: 3,
                    child: NestedScrollView(
                        physics: isOverlayShow
                            ? NeverScrollableScrollPhysics()
                            : AlwaysScrollableScrollPhysics(),
                        controller: _scrollController,
                        headerSliverBuilder: (context, innerScrolled) => [
                              SliverOverlapAbsorber(
                                handle: NestedScrollView
                                    .sliverOverlapAbsorberHandleFor(context),
                                sliver: SliverAppBar(
                                  automaticallyImplyLeading: false,
//                                  backgroundColor: ThemeUtils.getThemeColor(
//                                      context: context,
//                                      brightnessColor: Colors.grey[800],
//                                      darkColor: Colors.black87),
                                  title: _sliverHeaderWidget(),
                                  floating: false,
                                  elevation: 0.0,
                                  expandedHeight: 250,
                                  titleSpacing: 0.0,
                                  primary: false,
                                  pinned: true,
                                  toolbarHeight: 80,
                                  flexibleSpace: FlexibleSpaceBar(
                                    background: _flexibleSpaceWidget(),
                                    collapseMode: CollapseMode.parallax,
                                  ),
                                  bottom: CoinDetailTabWidget(
                                      controller: _tabController,
                                      onTap: (index) {
                                        _tabController.animateTo(index);
                                      }),
                                  forceElevated: innerScrolled,
                                ),
                              )
                            ],
                        body: TabBarView(
                          children: [
                            CoinDetailListWidget(allTransferRecordList),
                            CoinDetailListWidget(transferAccountRecordList),
                            CoinDetailListWidget(payeeRecordList),
                          ],
                          controller: _tabController,
                        ))),
                Positioned(
                  child: Offstage(
                    offstage: !isOverlayShow,
                    child: Container(
                      decoration: BoxDecoration(
                          color: Colors.grey[800],
                          borderRadius: BorderRadius.all(Radius.circular(10))),
                      width: MediaQuery.of(context).size.width * 3 / 4,
                      height: 120,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Padding(
                                padding: EdgeInsets.only(left: 15, top: 15),
                                child: Text(
                                  "${WXLang.$t("home_frozen_quantity", package: ModuleConfig.moduleName)}：",
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 15),
                                ),
                              ),
                              Spacer(),
                              Padding(
                                padding: EdgeInsets.only(right: 15, top: 16),
                                child: Text(
                                  "0.00000000 ${_bean.title}",
                                  style: TextStyle(
                                      color: Color(0xFFCCA881), fontSize: 15),
                                ),
                              ),
                            ],
                          ),
                          Container(
                            height: 1,
                            color: Colors.grey[600],
                            margin:
                                EdgeInsets.only(right: 15, left: 15, top: 15),
                          ),
                          Padding(
                            padding:
                                EdgeInsets.only(left: 15, top: 20, right: 20),
                            child: Text(
                              "${WXLang.$t("home_frozen_info_text", package: ModuleConfig.moduleName)}",
                              style: TextStyle(
                                  color: Colors.grey[500], fontSize: 12),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  right: 10,
                  top: 180,
                ),
                Positioned(
                  child: Row(
                    children: [
                      Expanded(
                          child: GestureDetector(
                        onTapDown: (down) {
                          print("TapDown");
                          buttonTransferColor = Colors.grey[200];
                          setState(() {});
                        },
                        onTapUp: (up) {
                          Future.delayed(Duration(milliseconds: 50), () {
                            print("TapUp");
                            buttonTransferColor = ThemeUtils.getThemeColor(
                                context: context,
                                brightnessColor: Colours.transfer_button,
                                darkColor: Colours.color_gold);
                            setState(() {});
                            WXNavigator.pushNamed(
                                context: context,
                                routeName: "/transfer_main",
                                arguments: _bean);
                          });
                        },
                        onTapCancel: () {
                          print("TapCancel");
                          buttonTransferColor = ThemeUtils.getThemeColor(
                              context: context,
                              brightnessColor: Colours.transfer_button,
                              darkColor: Colours.color_gold);
                          setState(() {});
                        },
                        child: Container(
                          height: 50,
                          alignment: Alignment.center,
                          margin: EdgeInsets.all(5),
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(6)),
                              color: buttonTransferColor),
                          child: Text(
                            "${WXLang.$t("home_transfer", package: ModuleConfig.moduleName)}",
                            style: TextStyle(color: Colors.white, fontSize: 14),
                          ),
                        ),
                      )),
                      Expanded(
                          child: GestureDetector(
                        onTapDown: (down) {
                          print("TapDown");
                          buttonReceivePaymentColor = Colors.grey[200];
                          setState(() {});
                        },
                        onTapUp: (up) {
                          Future.delayed(Duration(milliseconds: 50), () {
                            print("TapUp");
                            buttonReceivePaymentColor = ThemeUtils.getThemeColor(
                                context: context,
                                brightnessColor: Colours.payee_button,
                                darkColor: Colors.grey[800]);
                            setState(() {});
                            WXNavigator.pushNamed(
                                context: context,
                                routeName: "/collection_qr_code",
                                arguments: _bean);
                          });
                        },
                        onTapCancel: () {
                          print("TapCancel");
                          buttonReceivePaymentColor = ThemeUtils.getThemeColor(
                              context: context,
                              brightnessColor: Colours.payee_button,
                              darkColor: Colors.grey[800]);
                          setState(() {});
                        },
                        child: Container(
                          height: 50,
                          alignment: Alignment.center,
                          margin: EdgeInsets.all(5),
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(6)),
                              color: buttonReceivePaymentColor),
                          child: Text(
                            "${WXLang.$t("home_receive", package: ModuleConfig.moduleName)}",
                            style: TextStyle(color: Colors.white, fontSize: 14),
                          ),
                        ),
                      )),
                    ],
                  ),
                  bottom: 15,
                  left: 0,
                  right: 0,
                )
              ],
            ),
          ))), //
    );
  }

  _sliverHeaderWidget() {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.only(top: 25),
          alignment: Alignment.bottomCenter,
          child: Column(
            children: [
              Text(
                _bean.title,
                style: TextStyle(
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[200],
                        darkColor: Colors.white),
                    fontSize: 16),
              ),
              isFold
                  ? Text(
                      NumUtil.getNumByValueStr(_coinDetailBean.num,
                              fractionDigits: 8)
                          .toString(),
                      style: TextStyle(color: Color(0xFFCCA881), fontSize: 14),
                    )
                  : SizedBox(
                      width: 0,
                      height: 0,
                    )
            ],
          ),
        ),
        Padding(
            padding: EdgeInsets.only(left: 15, top: isFold ? 25 : 20),
            child: InkWell(
              child: Image.asset(ImageR.imagesActivityTitleBack,
                  width: 30,
                  height: 30,
                  color: ThemeUtils.getThemeColor(
                      context: context,
                      brightnessColor: Colors.grey[200],
                      darkColor: Colors.white),
                  fit: BoxFit.fill,
                  package: ModuleConfig.moduleName),
              onTap: () {
                Navigator.of(context).pop();
              },
            ))
      ],
    );
  }

  _flexibleSpaceWidget() {
    return Column(
      children: [
        Container(
          height: 175,
          width: double.infinity,
//          color: ThemeUtils.getThemeColor(
//              context: context,
//              brightnessColor: Colors.grey[800],
//              darkColor: Colors.black87),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.only(top: 85, left: 15),
                child: Text(
                  "${WXLang.$t("home_total_amount", package: ModuleConfig.moduleName)}(${_bean.title})",
                  style: TextStyle(
                      color: ThemeUtils.getThemeColor(
                          context: context,
                          brightnessColor: Colors.grey[200],
                          darkColor: Colors.white)),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 8, left: 15),
                child: Text(
                  NumUtil.getNumByValueStr(_coinDetailBean.num,
                          fractionDigits: 8)
                      .toStringAsFixed(6),
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
              ),
              Row(
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: 15, left: 15),
                    child: Text(
                      "≈${NumUtil.getNumByValueStr(_coinDetailBean.cnyMoney).toStringAsFixed(2)} CNY",
                      style: TextStyle(
                          color: ThemeUtils.getThemeColor(
                              context: context,
                              brightnessColor: Colors.grey[200],
                              darkColor: Colors.white),
                          fontSize: 12),
                    ),
                  ),
                  Spacer(),
                  Padding(
                    padding: EdgeInsets.only(top: 10, right: 30),
                    child: Text.rich(TextSpan(children: [
                      TextSpan(
                          text:
                              "${WXLang.$t("home_available", package: ModuleConfig.moduleName)} ${NumUtil.getNumByValueStr(_coinDetailBean.num).toStringAsFixed(6)} (${_bean.title})",
                          style: TextStyle(
                              color: ThemeUtils.getThemeColor(
                                  context: context,
                                  brightnessColor: Colors.grey[200],
                                  darkColor: Colors.white),
                              fontSize: 12)),
                      WidgetSpan(
                          child: InkWell(
                            child: Image(
                              image: AssetImage(ImageR.imagesFreezeHelpIcon,
                                  package: ModuleConfig.moduleName),
                              width: 25,
                              height: 25,
                              fit: BoxFit.cover,
                            ),
                            onTap: () {
                              isOverlayShow = !isOverlayShow;
                              setState(() {});
                            },
                          ),
                          alignment: PlaceholderAlignment.middle),
                    ])),
                  )
                ],
              )
            ],
          ),
        ),
        Container(
          height: 75,
          padding: EdgeInsets.only(left: 15, top: 5),
          width: double.infinity,
          color: ThemeUtils.getThemeColor(
              context: context,
              brightnessColor: Colors.grey[200],
              darkColor: Colors.grey[600]),
          child: Text(
            "${WXLang.$t("home_recent_transaction", package: ModuleConfig.moduleName)}",
            style: TextStyle(
                color: ThemeUtils.getThemeColor(
                    context: context,
                    brightnessColor: Colors.grey[600],
                    darkColor: Colors.grey[300]),
                fontSize: 12),
          ),
        ),
      ],
    );
  }

  void _onPageChanged(int index) {
    _tabController.animateTo(index);
  }

  @override
  void didAppear() {
    super.didAppear();
    _getTransferRecordList();
    print(
        "model======================>${SpUtil.getString(transfer_record_key)}");
  }

  _getTransferRecordList() {
    allTransferRecordList.clear();
    transferAccountRecordList.clear();
    payeeRecordList.clear();

    String transferData = SpUtil.getString(transfer_record_key);
    if (transferData.isEmpty) return;
    List list = json.decode(transferData);

    List<CoinDetailModel> allList = CoinDetailModel.fromList(list);
    //allTransferRecordList = CoinDetailModel.fromList(list);
    allList.forEach((bean) {
      if (_bean.title == bean.name) {
        allTransferRecordList.add(bean);
      }
    });

    allTransferRecordList.forEach((bean) {
      if (bean.transferType == "0") {
        transferAccountRecordList.add(bean);
      } else {
        payeeRecordList.add(bean);
      }
    });
//    transferAccountRecordList = CoinDetailModel.fromList(list);
    // payeeRecordList = CoinDetailModel.fromList(list);
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    _tabController?.dispose();
    _scrollController?.dispose();
    // _controller?.dispose();
  }
}
